<template>
  <div class="wallet">
    <!-- 未登录 -->
    <div v-if="!connectType">
      <h2 class="theme-color font-20 fontW-7 text-c mgt-20">{{$t('wallet.title')}}</h2>
      <div class="mgt-10 wallet_types">
        <img @click.stop="connectMetamask" src="../../assets/icon/meta.svg"/>
        <img @click.stop="connectWallet" src="../../assets/icon/walle.svg"/>
      </div>
      <p class="color-9 text-c fontW-b font-15">{{$t('wallet.tips')}}</p>
    </div>
    <!-- 已登陆 -->
    <div v-else class="loginBox mgt-20">
      <div class="loginContent">
        <div class="header-img flex-1">
          <img class="radius-50 mg-0 float-r" src="../../assets/header/header.jpg" alt="">
        </div>
        <div class="flex-3 text-c">
          <div class="fontW-9 color-f font-20">Eric xx</div>
          <div class="flex-n-center userName">
            <!-- <div class="font-15 fontW-b theme-color">{{ account | accountFormat }}</div> -->
            <div class="font-15 fontW-b theme-color">{{ showAccount }}</div>
            <div class="mgl-10"><img src="../../assets/icon/copy.svg" alt=""></div>
          </div>
          <div class="flex-n-center userName">
            <div class="font-15 theme-color">UID:{{Uid}}</div>
            <div class="mgl-10"><img src="../../assets/icon/copy.svg" alt=""></div>
          </div>
        </div>
        <div class="flex-1">
          <div class="flex-n-center font-15 logout" @click="loginOut">
            <img src="../../assets/icon/logout.svg" alt="">
            <div class="color-f fontW-b">{{$t('wallet.loginOut')}}</div>
          </div>
        </div>
      </div>
      <div class="person mgt-10 flex-n-center">
        <div class="item bg-f flex-n-center mg-0 border-r boxS-i-4" @click.stop="jumpToPerson">
          <div>
            <img src="../../assets/icon/person.svg" alt="">
          </div>
          <div class="font-15 fontW-9">{{$t('wallet.person')}}</div>
        </div>
        <div class="item bg-f flex-n-center mg-0 border-r boxS-i-4" @click.stop="jumpToSetting">
          <div><img src="../../assets/icon/setting.svg" alt=""></div>
          <div class="font-15 fontW-9">{{$t('wallet.setting')}}</div>
        </div>
      </div>
      <div class="ethBox">
        <div class="color-a font-15 fontW-9 mgtb-10 flex-s-between">
          <span>{{$t('wallet.total')}}</span>
          <span>$1,283.53USD</span>
        </div>
        <div class="ethTotal bg-f boxS-i-4 border-r">
          <div class="ethItem flex-s-around mgt-1">
            <div class="ethicon flex-1">
              <img src="../../assets/ETH/ETH.svg" alt="">
            </div>
            <div class="flex-2">
              <p class="font-15 fontW-9">ETH</p>
              <p class="color-45 font-10 fontW-7">Ethereum</p>
            </div>
            <div class="money flex-2">
              <p class="font-15 fontW-7">0.4719</p>
              <p class="font-10 fontW-7">$1283.53</p>
            </div>
          </div>
          <div class="ethItem flex-s-around mgt-1">
            <div class="ethicon flex-1">
              <img src="../../assets/ETH/Polygon_matic.svg" alt="">
            </div>
            <div class="flex-2">
              <p class="font-15 fontW-9">MATIC</p>
              <p class="color-45 font-10 fontW-7">Polygon</p>
            </div>
            <div class="money flex-2">
              <p class="font-15 fontW-7">0.3566</p>
              <p class="font-10 fontW-7">$1283.53</p>
            </div>
          </div>
          <div class="ethItem flex-s-around mgt-1">
            <div class="ethicon flex-1">
              <img src="../../assets/ETH/IMN.svg" alt="">
            </div>
            <div class="flex-2">
              <p class="font-15 fontW-9">IMN</p>
              <p class="color-45 font-10 fontW-7">Ethereum</p>
            </div>
            <div class="money flex-2">
              <p class="font-15 fontW-7">{{ImnAmount}}</p>
              <p class="font-10 fontW-7">$1283.53</p>
            </div>
          </div>
          <div class="ethItem flex-s-around mgt-1">
            <div class="ethicon flex-1">
              <img src="../../assets/ETH/WETH.svg" alt="">
            </div>
            <div class="flex-2">
              <p class="font-15 fontW-9">WETH</p>
              <p class="color-45 font-10 fontW-7">Ethereum</p>
            </div>
            <div class="money flex-2">
              <p class="font-15 fontW-7">0.4719</p>
              <p class="font-10 fontW-7">$1283.53</p>
            </div>
          </div>
        </div>
        <div class="mgtb-10 swapBox">
          <div class="swap float-r bg-theme flex-n-center border-r box-4"
          @click="showSwap">
            <div><img src="../../assets/icon/refresh.svg" alt=""></div>
            <div class="font-15 fontW-9">Swap</div>
          </div>
        </div>
        <div class="swapIframeBox bg-f-8" v-if="showSwapFlag" @click.stop="hideSwap">
          <iframe
            :src="'https://app.uniswap.org/#/swap?exactField=input&theme=dark&exactAmount=10&inputCurrency='+ account"
            width="100%"/>
        </div>
        <div class="pledgeBox">
          <el-input class="boxS-i-4 text-r" type="text" v-model="pledgeNum" placeholder="100.00"></el-input>
          <div class="flex-s-between pledef mgt-10">
            <div class="flex-s-between">
              <div><img src="../../assets/ETH/IMN_BG.svg" style="width: 25px;" alt=""></div>
              <div class="color-f font-15 fontW-7">IMN {{$t('wallet.pledge')}}</div>
            </div>
            <div class="pledge bg-theme border-r box-4 text-c">
              <div class="font-15 fontW-9" @click="hundlePledge">{{$t('wallet.pledge')}}</div>
            </div>
          </div>
          <div class="pd-5 boxS-i-4 font-15 fontW-b mgtb-10 flex-s-between bg-theme border-r">
            <div>{{$t('wallet.pledgeIncome')}}</div>
            <div>1313489</div>
          </div>
          <div class="pd-5 boxS-i-4 font-15 fontW-b mgtb-10 flex-s-between bg-theme border-r">
            <div>{{$t('wallet.withdrawableIncome')}}</div>
            <div>127987</div>
          </div>
        </div>
        <div>
          <p class="color-f font-15 fontW-7 mgb-10">{{$t('wallet.redemptionIncom')}}</p>
          <div>
            <el-input class="boxS-i-4 text-r" type="text" v-model="redemption" placeholder="100.00"></el-input>
          </div>
          <div class="redemptionsub mgt-10">
            <div class="pledge bg-theme border-r box-4 text-c">
              <div class="font-15 fontW-9" @click="hundleRedeem">{{$t('wallet.redemption')}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 语言切换 -->
    <div class="language">
      <div @click="hundleChangLanguage" class="languageItem flex-s-between border-r box-4">
        <div class="font-20 fontW-7 text-s">{{languageText}}</div>
        <div>
          <img src="../../assets/icon/language.svg" alt="">
        </div>
      </div>
    </div>
    <div class="languageChange" v-show="changLanguage">
      <div v-for="item in languageType" :key="item.id" @click="hundleChangLanguageItem(item)" class="changeItem border-r border-2 font-20 fontW-7 bg-f">{{ item.name }}</div>
    </div>
  </div>
</template>
<script>
import Web3 from 'web3'
import WalletConnectProvider from '@walletconnect/web3-provider'
import web3Tool from '../../Js/web3Tool'
// import DemoJson from '../../../static/contract/demo.json'
// import AbiAddress from '../../../static/contract/address'
import {MessagePormpt} from '../../Js/common'
// import { Message } from 'element-ui'
// import Web3Modal from 'web3modal'
const languageType = [
  {id: 0, type: 'zh-cn', name: '简体中文'},
  {id: 1, type: 'en', name: 'English'},
  {id: 2, type: 'zh-tw', name: '繁体中文'},
  {id: 3, type: 'ru', name: 'Русский'}
]
export default {
  data () {
    return {
      changLanguage: false,
      pledgeNum: '',
      redemption: '',
      languageType: languageType,
      languageText: '',
      connectType: false,
      account: '',
      showSwapFlag: false,
      isConnect: false,
      ImnAmount: '--',
      ethereum: null,
      DemoContract: {},
      Uid: 0
    }
  },
  async created () {
    await this.$nextTick()
    // console.log(web3Tool, web3Tool.account, DemoJson, 'demo', AbiAddress)
    // console.log(web3Tool.isConnected, this.$cookies.get('wallet_acount'))
    if (Number(this.$cookies.get('wall_type')) === 2) {
      this.connectType = JSON.parse(localStorage.getItem('walletconnect')).connected
      this.account = this.$cookies.get('wallet_acount')
    } else {
      if (Object.keys(web3Tool).length === 0) {
        this.connectType = false
      } else {
        this.connectType = true
        this.account = web3Tool.account
      }
    }
    window.addEventListener('load', async () => {
      try {
        await window.ethereum.enable()
      } catch (error) {}
    })
    web3Tool.getBalance()
    this.createContract()
  },
  computed: {
    showAccount () {
      return (
        this.account.substring(0, 4) + '···' + this.account.substring(this.account.length - 4)
      )
    }
  },
  mounted () {
    // console.log((this.$i18n.locale), web3Tool, web3Tool.isConnected, this.$cookies.get('wallet_acount'))
    this.languageType.forEach((item) => {
      if (item.type === this.$i18n.locale) {
        this.languageText = item.name
      }
    })
    if (this.$cookies.get('uid')) {
      // console.log(this.$cookies.get('uid'))
      this.Uid = this.$cookies.get('uid')
    }
    this.accountsChanged()
    // this.createContract()
  },
  methods: {
    // createContract: function () {
    //   // this.contract = new this.web3.eth.Contract(DemoJson.abi, this.account)
    //   this.DemoContract = new web3Tool.web3.eth.Contract(DemoJson.abi, AbiAddress.demoAddress)
    //   this.checkBlanceOf()
    //   this.checkStakingPool()
    //   // this.checkRedeem()
    //   // this.hundlePushBlock()
    //   // this.getPledgemount()
    //   // console.log(this.DemoContract, JSON.stringify(DemoJson.abi))
    // },
    hundlePledge: function () {
      if (this.pledgeNum === '') {
        // Message.warning('您还未输入质押金额')
        let langObj = {
          zh_cn: '您还未输入质押金额',
          en: 'You have not entered the pledge amount',
          ru: 'Вы не ввели сумму залога',
          zh_tw: '您還未鍵入質押金額'
        }
        MessagePormpt(this.langType, langObj)
        return false
      }
      const Num = web3Tool.web3.utils.toWei(this.pledgeNum, 'ether')
      // console.log(Num)
      this.DemoContract.methods.stake(Num).send({from: this.account}, (err, res) => {
        console.log(err, res, 'stake')
      })
    },
    // 查询余额 imn
    checkBlanceOf: async function () {
      await this.DemoContract.methods.balanceOf(this.account).call({}, (err, res) => {
        console.log('balanceof', res, err)
        if (res) {
          this.ImnAmount = web3Tool.web3.utils.fromWei(res, 'ether')
        }
      })
    },
    // 查询质押金额 区块高度
    checkStakingPool: async function () {
      console.log(this.account)
      await this.DemoContract.methods.stakingpool(this.account).call({}, (err, res) => {
        console.log('checkStakingPool', res, err)
      })
    },
    // 查询质押收益
    getPledgemount: async function () {
      await this.DemoContract.methods.rewarding().call({from: this.account}, (err, res) => {
        console.log('rewarding', res, err)
      })
    },
    // 赎回（全部）
    hundleRedeem: async function () {
      await this.DemoContract.methods.redeem().send({from: this.account}, (err, res) => {
        console.log('checkRedeem', res, err)
        if (res) {
          this.checkBlanceOf()
        }
      })
    },
    hundlePushBlock: async function () {
      await this.DemoContract.methods.pushBlock().send({from: this.account}, (err, res) => {
        console.log('pushBlock', res, err)
        if (res) {
          this.getPledgemount()
        }
      })
    },
    connectMetamask: async function () {
      let ethereum = window.ethereum
      if (ethereum) {
        this.ethereum = ethereum
        this.accounts = await ethereum.request({
          method: 'eth_requestAccounts'
        })
        this.account = this.accounts[0]
        // console.log(this.accounts)
        this.isConnect = true
        this.connectType = true
        this.$cookies.set('isConnect', true)
        this.$cookies.set('wallet_acount', this.account)
        this.$cookies.set('wall_type', 1)
        this.loginByAccount()
      } else {
        window.open('https://metamask.io/download.html', '_blank')
      }
    },
    connectWallet: async function () {
      /* eslint-disable */
      const that = this
      this.$cookies.set('wall_type', 2)
      // const acc = web3Tool.init_web3()
      // console.log('acc', acc)
      that.provider = new WalletConnectProvider({
        rpc: {
          1: 'https://mainnet.infura.io/v3/9c58fe08a1e348e2be986a43f48902f4',
          56: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
          97: 'https://data-seed-prebsc-1-s3.binance.org:8545',
          3: 'https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
          4: 'https://rinkeby.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'
        }
      })
      that.provider.on('accountsChanged', (accounts) => {
        console.log(accounts, 'connectWallet')
        this.$cookies.set('wallet_acount', accounts)
      })
      that.provider.on('chainChanged', (chainId) => {
        console.log(chainId)
      })
      console.log('用户监听变化')

      that.web3 = new Web3(that.provider)
      const networkId = new that.web3.eth.net.getId()
      await that.provider.enable()
        .then(function (accounts) {
          console.log(accounts)
          that.account = accounts[0]
          this.isConnect = true
        })
        .catch(function (reason) {
          that.account = ''
          console.log('登录不成功')
          this.isConnect = false
          this.$cookies.remove('wall_type', '')
        })
    },
    // 退出
    loginOut: function () {
      if (Number(this.$cookies.get('wall_type')) === 2) {
        web3Tool.WalletConnect_del()
      } else {
        if (window.ethereum) {
          // let ethereum = window.ethereum
          // ethereum.on('disconnect', () => {
          //   console.log('MetaMask discconnected')
          // })
        }
        // this.$cookies.remove('wall_type')
        // this.$cookies.remove('wallet_acount')
        web3Tool.WalletConnect_del()
      }
      this.connectType = false
    },
    accountsChanged: async function () {
      const that = this
      ethereum.on('accountsChanged', function (accounts) {
        that.$cookies.set('wallet_acount', accounts[0])
        console.log(that.$cookies.get('wallet_acount'), accounts)
        // await _gasthis.getBalance()
        // await _gasthis.getPrice($cookies.get('wallet_chain'))
        that.account = accounts[0]
        // _gasthis.account_listen(from_addr)
        // location.reload()
        // console.log(accounts[0])
      })
    },
    // 切换语言
    hundleChangLanguage: function () {
      this.changLanguage = !this.changLanguage
    },
    // 切换语言
    hundleChangLanguageItem: function (item) {
      this.$i18n.locale = item.type
      this.languageText = item.name
      this.changLanguage = !this.changLanguage
      localStorage.setItem('language', item.type)
    },
    jumpToSetting: function () {
      this.$emit('changeDrawerStatus', false)
      this.$router.push({
        path: '/setting'
      })
    },
    jumpToPerson: function () {
      this.$emit('changeDrawerStatus', false)
      this.$router.push({
        path: '/person_collection',
        query: {
          type: 1
        }
      })
    },
    showSwap: function () {
      this.showSwapFlag = !this.showSwapFlag
    },
    hideSwap: function () {
      this.showSwapFlag = !this.showSwapFlag
    },
    loginByAccount: function () {
      this.$loading.show()
      let data = new FormData()
      data.append('address', this.account)
      const params = {
        data,
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      }
      this.$Api.Index.LoginByAccount(params, data)
        .then(res => {
          this.$loading.hide()
          console.log(res, JSON.stringify(res))
          this.Uid = res.data.uid
          this.$cookies.set('token', res.data.token)
          this.$cookies.set('uid', res.data.uid)
        })
        .catch(err => {
          this.$loading.hide()
          console.log(err, JSON.stringify(err))
        })
    }
  }
}
</script>
<style lang="less" scoped>
  .wallet {
    width: 100%;
    h2 {
      width: 100%;
    }
    .wallet_types{
      img {
        display: block;
        margin: 10px auto;cursor: pointer;
      }
    }
    .loginBox {
      .loginContent {
        display: flex;
        .header-img {
          margin-left: 5%;
          img {
            width: 50px;
            height: 50px;
            display: block;
          }
        }
        .userName {
          height: 20px;
          line-height: 20px;
          div:nth-child(2) {
            cursor: pointer;
          }
        }
        .logout {
          cursor: pointer;
        }
      }
      .person {
        width: 270px;
        height: auto;
        overflow: hidden;
        .item {
          width: 45%;
          height: 37px;
          cursor: pointer;
          img  {
            margin-top: 15px;
          }
        }
      }
      .ethBox {
        width: 259px;
        height: auto;
        margin: 0 auto;
        .ethTotal {
          .ethItem {
            width: 90%;
            // margin: 15px auto;
            padding: 10px 0;
            .ethicon {
              img {
                width: 30px;
                height: 30px;
                display: block;
                margin: 0 auto;
              }
            }
            .money {
              p {
                text-align: right;
              }
            }
          }
        }
        .swapBox {
          overflow: hidden;
          .swap {
            width: 89px;
            height: 25px;
            cursor: pointer;
          }
        }
        .swapIframeBox {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 999;
          width: 100%;
          height: 100%;
          overflow: hidden;
          iframe {
            width: auto;
            height: auto;
            border: 0px;
            margin: 0px auto 0.5rem;
            display: block;
            border-radius: 10px;
            max-width: 600px;
            min-width: 450px;
            min-height: 550px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
        }
        .pledgeBox {
          .pledef {
            overflow: hidden;
          }
          .pledge {
            width: 89px;
            height: 25px;
            line-height: 25px;
            cursor: pointer;
          }
        }
        .redemptionsub {
          div {
            float: right;
            width: 89px;
            height: 25px;
            line-height: 25px;
            cursor: pointer;
          }
        }
      }
    }
    .language {
      position: absolute;
      bottom: 30px;
      left: 0;
      width: 100%;
      cursor: pointer;
      .languageItem {
        width: 259px;
        height: 39px;
        margin: 0 auto;
        padding: 0 10px;
        background: #7DE9FF;
      }
    }
    .languageChange {
      position: absolute;
      bottom: 70px;
      left: 0;
      width: 100%;
      cursor: pointer;
      .changeItem {
        width: 259px;
        height: 39px;
        line-height: 39px;
        margin: 0 auto;
        padding: 0 10px;
      }
    }
  }
  /deep/.el-input__inner {
    text-align: right;
  }
</style>
